package design.behavior_observer;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class DemoObserver {
    @Test
    public void test() {
        Subject subject=new WechatGzh();
        subject.registerObserver(new UserA());
        subject.notifyObservers("发布公众号文章");
    }

    //观察者接口
    public interface Observer {
        void update(Object msg);
    }
    //具体的观察者
    public static class UserA implements Observer {
        @Override
        public void update(Object msg) {
            System.out.println("userA 收到消息："+ msg);
        }
    }
    //抽象的主题接口
    public interface Subject {
        void registerObserver(Observer observer);
        void notifyObservers(Object msg);
    }

    //具体的主题接口，此处以公众号为例
    public class WechatGzh implements Subject {
        private List<Observer> observers = new ArrayList();

        @Override
        public void registerObserver(Observer observer) {
            observers.add(observer);
        }
        @Override
        public void notifyObservers(Object msg) {
            for (Observer observer : observers){
                observer.update(msg);
            }
        }
    }
}
